import React, { useCallback, useContext, useEffect, useState } from 'react'
import { createBrowserHistory } from 'history'
import { ReactNode, ReactElement } from 'react'
import RouterContext from './RouterContext'

interface IRouter {
  history: ReturnType<typeof createBrowserHistory>
  children?: ReactElement
}

export default function Router({ history, children }: IRouter) {
  console.log(history)
  const [location, setLocation] = useState<any>({})

  const computeRootMatch = (pathname: string) => {
    return { path: "/", url: "/", params: {}, isExact: pathname === "/" }
  }



  useEffect(() => {
    setTimeout(() => {
      history.push('/a')
    }, 2000)
    console.log('useEffect history')
    const unListen = history.listen(({ location, action }) => {
      console.log('location', location)
      console.log('action', action)
      setLocation(location)
    })
    return () => {
      unListen()
    }
  }, [])
  return (
    <RouterContext.Provider value={{
      history: history,
      location: location,
      match: computeRootMatch(location.pathname),
    }}>
      {children}
    </RouterContext.Provider>
  )
}
